package com.gouaixin.bee.beeframework2.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.tool.MD5Util;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.RandomUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

import cn.bmob.im.BmobChatManager;
import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Administrator on 2015/3/5.
 */
//注册界面
public class A2_ReginActivity extends Activity {
    Context context = A2_ReginActivity.this;

    TextView title;//标题
    ImageView back;//返回

    EditText nameET;//昵称
    TextView ageET;//年龄
    CheckBox manRB;//男
    CheckBox womanRB;//女

    Button reginBT;//立即注册

    String name;
    String age;
    String gender = "男";
    int mySexType = 0;//0男，1女

    String password;
    String id;

    BmobChatUser bu;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a2_regin);

        initHead();

        initContent();

    }

    private void initContent() {
        nameET = (EditText) findViewById(R.id.name);
        ageET = (TextView) findViewById(R.id.age);
        manRB = (CheckBox) findViewById(R.id.man);
        womanRB = (CheckBox) findViewById(R.id.woman);
        reginBT = (Button) findViewById(R.id.regin);


        ageET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                Intent it=new Intent(context,dialogActivity_nianlin.class);
//                it.putExtra("flag",1);
//                startActivityForResult(it,1);
                Intent it = new Intent(context, dialogActivity_nianlin.class);
                it.putExtra("flag", "1");
                startActivityForResult(it, 1);
            }
        });

        manRB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    womanRB.setChecked(false);
                    gender = "男";
                    mySexType=0;
                } else {
                    womanRB.setChecked(true);
                }
            }
        });

        womanRB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    manRB.setChecked(false);
                    gender = "女";
                    mySexType=1;
                } else {
                    manRB.setChecked(true);
                }
            }
        });

        reginBT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                regin();

            }
        });

    }

    //注册的主方法
    private void regin() {
        //获取编辑框数据
        name = nameET.getText().toString();
        age = ageET.getText().toString();
        if (name.equals("") || age.equals("")||age.equals("请选择您的年龄")) {
            Toast.makeText(context, "信息填写不完整", Toast.LENGTH_SHORT).show();
            return;
        }
        if (name.length()>20) {
            Toast.makeText(context, "昵称长度不能超过20位", Toast.LENGTH_SHORT).show();
            return;
        }



        //随机生成id和password
        id = RandomUtils.getRandomNumbers(8);
        password = RandomUtils.getRandomNumbers(4);

        android.util.Log.e("Demo", "提交注册数据:\tjid:" + id + "\tpassword:" + password);


        //创建一个用户
        bu = new BmobChatUser();
        bu.setUsername(id);
        bu.setPassword(password);
        //注册USER
        bu.signUp(context, new SaveListener() {

            @Override
            public void onSuccess() {
                signUpSuccess();
            }

            @Override
            public void onFailure(int arg0, String arg1) {
                mLog.e("注册失败:" + arg1);
            }


        });

    }

    //注册失败
    private void signUpFailure() {
    }

    //注册成功
    private void signUpSuccess() {
        Toast.makeText(context, "注册成功", Toast.LENGTH_SHORT).show();

        // 注册成功，需要把用户绑定到当前这台设备中
        BmobUserManager userManager = BmobUserManager.getInstance(context);
        userManager.bindInstallationForRegister(bu.getUsername());

        //注册成功时，再保存拓展的USER对象
        USER myuser = BmobUser.getCurrentUser(context, USER.class);
        myuser.setName(name);
        myuser.setGender(gender);
        myuser.setAge(age);

        mLog.e(new Gson().toJson(myuser));

        myuser.update(context, new UpdateListener() {
            @Override
            public void onSuccess() {
                updateSuccess();
            }

            @Override
            public void onFailure(int i, String s) {
                android.util.Log.e("Demo", "更新拓展的USER数据:失败：" + s);
            }
        });
    }

    BmobUserManager mBmobUserManager;
    BmobChatManager mBmobChatManager;
    BmobChatUser currentUser;

    //更新成功
    private void updateSuccess() {
        android.util.Log.e("Demo", "提交注册数据:成功\tcid:" + id + "\tpassword:" + password);
        PreferencesUtils.clear(context);//清除上个用户的缓存
        DbUtils db = DbUtils.create(context);
        db.configAllowTransaction(true);
        db.configDebug(true);
        try {
            db.dropDb();
        } catch (DbException e) {
            mLog.e(e.getMessage());
        }

        PreferencesUtils.putString(context, "cid", id);
        PreferencesUtils.putString(context, "password", password);
        PreferencesUtils.putString(context, "gender", gender);
        PreferencesUtils.putInt(context, "sexType", mySexType);
        PreferencesUtils.putString(context, "cname", name);

        initMD5(id);







        //测试时，默认直接跳转到登录界面
//        android.util.Log.e("Demo", "进入到登录界面");
//        Intent mainIntent = new Intent().setClass(A2_ReginActivity.this, A3_LoginActivity.class);
//        startActivity(mainIntent);
//        finish();
        android.util.Log.e("Demo", "默认执行登录");
        mBmobUserManager=BmobUserManager.getInstance(context);
        mBmobUserManager.login(id,password,new SaveListener() {
            @Override
            public void onSuccess() {
                //获取当前登录用户信息
                android.util.Log.e("Demo", "默认登录成功");
                currentUser = mBmobUserManager.getCurrentUser();
//                    Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show();

                //测试时，默认直接跳转到主界面
                android.util.Log.e("Demo", "进入到主界面");
                Intent mainIntent = new Intent().setClass(context, MyMainActivity.class);
                startActivity(mainIntent);
                finish();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show();

                android.util.Log.e("Demo", "进入注册登录界面");
                Intent it = new Intent().setClass(context, LeadActivity.class);
                startActivity(it);
                finish();



            }
        });


    }

    private void initMD5(String cid) {
        String yaun=cid+"sharkou";
        mLog.e("MD5:原文="+cid);

        String md5= MD5Util.string2MD5(cid);
        mLog.e("MD5:编码="+md5);

        PreferencesUtils.putString(context, "md5", md5);


    }

    private void initHead() {
        title = (TextView) findViewById(R.id.title);
        title.setText("用户注册");
        title.setBackgroundDrawable(null);

        back = (ImageView) findViewById(R.id.back);
        Resources resources = getBaseContext().getResources();
        Drawable drawable = resources.getDrawable(R.drawable.home_search_left);
        back.setBackgroundDrawable(drawable);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                android.util.Log.e("Demo", "返回到登录注册界面");
                Intent mainIntent = new Intent().setClass(A2_ReginActivity.this, A1_SigninActivity.class);
                startActivity(mainIntent);
                finish();

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (data != null) {
                String curr_year = data.getStringExtra("str");
                ageET.setText(curr_year);
            }

        }

    }
}
